package com.basic.modules.ykf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.basic.common.utils.R;
import com.basic.modules.sys.entity.SysUserEntity;
import com.basic.modules.sys.service.SysUserService;
import com.basic.modules.ykf.entity.*;
import com.basic.modules.ykf.model.CustomModel;
import com.basic.modules.ykf.model.ShopModel;
import com.basic.modules.ykf.model.SubModel;
import com.basic.modules.ykf.model.UserModel;
import com.basic.modules.ykf.service.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("testService")
public class TestServiceImpl implements TestService {
    @Autowired
    private YkfDictService dictService;

    @Autowired
    private YkfDictDetailService ykfDictDetailService;

    @Autowired
    private YkfCustomerShopService shopService;

    @Autowired
    private YkfCustomerService customerService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private YkfCustomerSubAccountService subAccountService;

    String url1 = "http://47.98.189.85:8008/manage?page%5Bsize%5D=2000&page%5Bindex%5D=1&project%5Bpwd%5D=0&sort%5BinOn%5D=-1&_u_=5bc9a4e21d63ac131c19f0cf&_t_=1722999454173&_s_=d9960b6335f91a09ddfd6971741a4c43";
    String url2 = "http://47.98.189.85:8008/customer?page%5Bsize%5D=2000&page%5Bindex%5D=1&filter%5Bstate%5D=true&sort%5Bon%5D=-1&_u_=5bc9a4e21d63ac131c19f0cf&_t_=1723007800473&_s_=3e08000e7fc1d4a49bafdc65a6632706";
    String url3 = "http://47.98.189.85:8008/custom?page%5Bsize%5D=4000&page%5Bindex%5D=1&sort%5B_id%5D=-1&_u_=5bc9a4e21d63ac131c19f0cf&_t_=1723041594381&_s_=371fe14da7e433f75d2c328ccb69e9d9";
    String url4 = "http://47.98.189.85:8008/subuser?page%5Bsize%5D=1000&page%5Bindex%5D=" + "INDEX" + "&filter%5Ballocation%5D=false&sort%5Bstate%5D=-1&sort%5B_id%5D=-1&_u_=5bc9a4e21d63ac131c19f0cf&_t_=1723174589667&_s_=7b563a032d5296d94edb587f60cc9ba6";

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public R importData() {
        String s = HttpUtil.get(url1);
        String items = JSONUtil.parse(s).getByPath("items", String.class);
        Gson gson = new Gson();
        List<UserModel> list = gson.fromJson(items, new TypeToken<List<UserModel>>() {
        }.getType());

        String s2 = HttpUtil.get(url2);
        String items2 = JSONUtil.parse(s2).getByPath("items", String.class);
        List<ShopModel> list2 = gson.fromJson(items2, new TypeToken<List<ShopModel>>() {
        }.getType());

        Map<String, String> departmentMap = dictMap("department");
        Map<String, String> postMap = dictMap("post");
        Map<String, String> customGroupMap = dictMap("customGroup");
        Map<String, String> customPostTypeMap = dictMap("customPostType");
        Map<String, String> platformMap = dictMap("platform");
        Map<String, String> shopTypeMap = dictMap("shopType");
        Map<String, String> marketTypeMap = dictMap("marketType");
        Map<String, String> expendTypeMap = dictMap("expandType");
        Map<String, String> customTypeMap = dictMap("customType");
        Map<String, String> serviceShiftMap = dictMap("serviceShift");
        Map<String, String> fitRatioMap = dictMap("fitRatio");
        List<SysUserEntity> userEntityList = new ArrayList<>();
        Map<String, SysUserEntity> userMap = new HashMap<>();

        Map<String, String> customMap = new HashMap<>();
        Map<String, String> customShopMap = new HashMap<>();
        getCustomData(customMap, customShopMap);

        //保存用户
        for (UserModel model : list) {
            SysUserEntity user = new SysUserEntity();
            user.setUsername(model.getMobile());
            user.setName(model.getXm());
            String salt = RandomStringUtils.randomAlphanumeric(20);
            user.setPassword(new Sha256Hash("123456", salt).toHex());
            user.setSalt(salt);
            if (StrUtil.isNotBlank(model.getInOn())) {
                user.setEntryDate(DateUtil.parseDate(model.getInOn()));
            }
            user.setFlowerName(model.getName());
            user.setSex(StrUtil.equals(model.getSex(), "true") ? "男" : "女");
            user.setNo(model.getNo());
            user.setDeptNo(model.getDepart());
            user.setDeptName(departmentMap.get(model.getDepart()));
            user.setPostNo(model.getPost());
            user.setPestName(postMap.get(model.getPost()));
            user.setOnDutyStatus(StrUtil.equals(model.getStatus(), "true") ? 1 : 0);
            user.setSendDepartMsg(StrUtil.equals(model.getLeaveSms(), "true") ? 1 : 0);
            user.setBecomeRegularStatus(StrUtil.equals(model.getZzStatus(), "true") ? 1 : 0);
            if (StrUtil.isNotBlank(model.getZzOn())) {
                user.setBecomeRegulardDate(DateUtil.parseDate(model.getZzOn()));
            }
            user.setCompanyNo("");
            user.setCompanyName("");
            user.setMobile(model.getMobile());
            user.setStatus(1);
            user.setGroupNo(model.getFormation());
            user.setCustomGroup(model.getGroup());
            user.setCustomGroupName(customGroupMap.get(model.getGroup()));
            user.setCustomPostType(model.getType());
            user.setCustomPostTypeName(customPostTypeMap.get(model.getType()));
            user.setOldId(model.get_id());
            sysUserService.save(user);
            userMap.put(model.get_id(), user);
        }
        Map<String, Long> cusIds = new HashMap<>();
        for (ShopModel model : list2) {
            Long customerId = null;
            if (!cusIds.containsKey(model.getCname())) {
                YkfCustomerEntity customer = new YkfCustomerEntity();
                String customerNo = customMap.get(model.getCname());
                if (StrUtil.isNotBlank(customerNo)) {
                    customer.setCustomerNo(customerNo);
                } else {
                    customer.setCustomerNo(model.getCname());
                }
                customer.setCustomerName(model.getCname());
                customerService.save(customer);
                customerId = customer.getCustomerId();
                cusIds.put(model.getCname(), customerId);
            } else {
                customerId = cusIds.get(model.getCname());
            }
            YkfCustomerShopEntity shop = new YkfCustomerShopEntity();
            shop.setCustomerId(customerId);
            shop.setShopNo(customShopMap.get(model.getName()));
            shop.setCooperateStatus(1);

            if (StrUtil.isNotBlank(model.getOn())) {
                shop.setFirstStartDate(DateUtil.parseDate(model.getOn()));
            }
            shop.setPlatformNo(model.getPlatform());
            shop.setPlatformName(platformMap.get(model.getPlatform()));

            shop.setShopTypeNo(model.getShoptype());
            shop.setShopTypeName(shopTypeMap.get(model.getShoptype()));
            shop.setShopName(model.getName());
            shop.setFeeModel(0);
            shop.setMarketTypeNo(model.getMarketType());
            shop.setMarketTypeName(marketTypeMap.get(model.getMarketType()));
            shop.setExpandTypeNo(model.getExpandType());
            shop.setExpandTypeName(expendTypeMap.get(model.getExpandType()));
            shop.setShopLinkUrl(model.getUrl());
            if (StrUtil.isNotBlank(model.getStart())) {
                shop.setStartDate(DateUtil.parseDate(model.getStart()));
            }
            if (StrUtil.isNotBlank(model.getEnd())) {
                shop.setEndDate(DateUtil.parseDate(model.getEnd()));
            }
            shop.setExcludingRefunds(StrUtil.equals(model.getRejectRefund(), "true") ? 1 : 0);
            shop.setCustomTypeNo(model.getServcieType());
            shop.setCustomTypeName(customTypeMap.get(model.getServcieType()));
            shop.setServiceShiftNo(model.getServiceShift());
            shop.setServiceShiftName(serviceShiftMap.get(model.getServiceShift()));
            if (StrUtil.isNotBlank(model.getBaseSalary())) {
                shop.setBaseSalary(new BigDecimal(model.getBaseSalary()));
            }
            if (StrUtil.isNotBlank(model.getExtract())) {
                shop.setCommission(new BigDecimal(model.getExtract()));
            }
            if (StrUtil.isNotBlank(model.getConsultNum())) {
                shop.setConsultPeopleNum(new BigDecimal(model.getConsultNum()));
            }
            if (StrUtil.isNotBlank(model.getConversionRate())) {
                shop.setConversionRate(new BigDecimal(model.getConversionRate()));
            }
            if (StrUtil.isNotBlank(model.getResponseTime())) {
                shop.setResponseSecond(new BigDecimal(model.getResponseTime()));
            }
            shop.setContacts(model.getContactname());
            shop.setQq(model.getQQ());
            shop.setWechat(model.getWexin());
            shop.setDing(model.getDd());
            shop.setPhone(model.getTel());
            shop.setFitRatioNo(model.getFit());
            shop.setFitRatioName(fitRatioMap.get(model.getFit()));
            shop.setStoreLiaison(model.getUsername());
            shop.setOldId(model.get_id());
            SysUserEntity sysUser = userMap.get(model.getUserid());
            if (ObjectUtil.isNotEmpty(sysUser)) {
                shop.setCreateUserId(sysUser.getUserId());
                shop.setCreateUserName(sysUser.getName());
            }
            shop.setRemark(model.getNote());
            shopService.save(shop);
        }
        return R.ok(userEntityList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void importData2() {
        List<YkfCustomerSubAccountEntity> saveList = new ArrayList<>();
        Map<String, String> exNameMap = dictMap("exName");
        for (int i = 1; i <= 15; i++) {
            String s = HttpUtil.get(url4.replace("INDEX", StrUtil.toString(i)));
            String items = JSONUtil.parse(s).getByPath("items", String.class);
            Gson gson = new Gson();
            List<SubModel> list = gson.fromJson(items, new TypeToken<List<SubModel>>() {
            }.getType());
            if (ObjectUtil.isNotEmpty(list)) {
                for (SubModel model : list) {
                    String customerId = model.getCustomerId();
                    QueryWrapper<YkfCustomerShopEntity> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(YkfCustomerShopEntity::getOldId, customerId)
                            .last("limit 1");
                    YkfCustomerShopEntity shop = shopService.getOne(queryWrapper);
                    if (ObjectUtil.isNotEmpty(shop)) {
                        if (ObjectUtil.isNotEmpty(model.getCs())) {
                            for (SubModel.SubDetail c : model.getCs()) {
                                YkfCustomerSubAccountEntity subAccount = new YkfCustomerSubAccountEntity();
                                BeanUtil.copyProperties(shop, subAccount);
                                if (ObjectUtil.isNotEmpty(shop.getCustomerId())) {
                                    YkfCustomerEntity customerEntity = customerService.getById(shop.getCustomerId());
                                    if (ObjectUtil.isNotEmpty(customerEntity)) {
                                        subAccount.setCustomerId(customerEntity.getCustomerId());
                                        subAccount.setCustomerName(customerEntity.getCustomerName());
                                    }
                                }
                                subAccount.setAccountNo(model.getSubname());
                                subAccount.setAccountName(model.getSubname());
                                subAccount.setAccountPassword(model.getSubpass());
                                subAccount.setStatus(1);
                                if (StrUtil.isNotBlank(c.getStart())) {
                                    subAccount.setStartDate(DateUtil.parseDate(c.getStart()));
                                }
                                if (StrUtil.isNotBlank(c.getEnd())) {
                                    subAccount.setEndDate(DateUtil.parseDate(c.getEnd()));
                                }
//                                subAccount.setAllocationRuleId(ykfCustomerSubAccount.getAllocationRuleId());
                                subAccount.setExName(c.getExName());
                                subAccount.setExNameLabel(exNameMap.get(c.getExName()));

                                if (StrUtil.isNotBlank(c.getBaseSalary())) {
                                    subAccount.setConventionSalary(new BigDecimal(c.getBaseSalary()));
                                } else {
                                    subAccount.setConventionSalary(BigDecimal.ZERO);
                                }
                                if (StrUtil.isNotBlank(c.getExtract())) {
                                    subAccount.setCommissionRatio(new BigDecimal(c.getExtract()));
                                } else {
                                    subAccount.setCommissionRatio(BigDecimal.ZERO);
                                }
                                subAccount.setSendSmsSign(1);
                                QueryWrapper<SysUserEntity> userEntityQueryWrapper = new QueryWrapper<>();
                                userEntityQueryWrapper.lambda().eq(SysUserEntity::getOldId, c.getCsId())
                                        .last("limit 1");
                                SysUserEntity sysUser = sysUserService.getOne(userEntityQueryWrapper);
                                if (ObjectUtil.isNotEmpty(sysUser)) {
                                    subAccount.setName(sysUser.getName());
                                    subAccount.setFlowerName(sysUser.getFlowerName());
                                    subAccount.setUserId(sysUser.getUserId());
                                }
                                subAccount.setConfirmStatus(StrUtil.equals(c.getStatus(), "true") ? 1 : 0);
                                subAccount.setOldId(model.get_id());
                                subAccount.setOldSubId(c.get_id());
                                saveList.add(subAccount);
                            }
                        } else {
                            YkfCustomerSubAccountEntity subAccount = new YkfCustomerSubAccountEntity();
                            BeanUtil.copyProperties(shop, subAccount);
                            if (ObjectUtil.isNotEmpty(shop.getCustomerId())) {
                                YkfCustomerEntity customerEntity = customerService.getById(shop.getCustomerId());
                                if (ObjectUtil.isNotEmpty(customerEntity)) {
                                    subAccount.setCustomerId(customerEntity.getCustomerId());
                                    subAccount.setCustomerName(customerEntity.getCustomerName());
                                }
                            }
                            subAccount.setAccountNo(model.getSubname());
                            subAccount.setAccountName(model.getSubname());
                            subAccount.setAccountPassword(model.getSubpass());
                            subAccount.setOldId(model.get_id());
                            subAccount.setStatus(1);
                            saveList.add(subAccount);
                        }
                    }
                }
            }
        }
        subAccountService.saveBatch(saveList);
    }

    private void getCustomData(Map<String, String> customMap, Map<String, String> customShopMap) {
        String s = HttpUtil.get(url3);
        String items = JSONUtil.parse(s).getByPath("items", String.class);
        Gson gson = new Gson();
        List<CustomModel> list = gson.fromJson(items, new TypeToken<List<CustomModel>>() {
        }.getType());

        if (ObjectUtil.isNotEmpty(list)) {
            for (CustomModel item : list) {
                customMap.put(item.getName(), item.get_id());
                if (ObjectUtil.isNotEmpty(item.getItems())) {
                    for (CustomModel.CustomDetailModel itemItem : item.getItems()) {
                        customShopMap.put(itemItem.getName(), itemItem.get_id());
                    }
                }
            }
        }
    }

    private Map<String, String> dictMap(String dictNo) {
        QueryWrapper<YkfDictEntity> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.lambda().eq(YkfDictEntity::getDictNo, dictNo);
        dictQueryWrapper.last("limit 1");
        YkfDictEntity dict = dictService.getOne(dictQueryWrapper);
        if (ObjectUtil.isNotEmpty(dict)) {
            QueryWrapper<YkfDictDetailEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(YkfDictDetailEntity::getDictId, dict.getDictId())
                    .orderByAsc(YkfDictDetailEntity::getSort);
            List<YkfDictDetailEntity> list = ykfDictDetailService.list(queryWrapper);
            if (ObjectUtil.isNotEmpty(list)) {
                Map<String, String> map = new HashMap<>();
                for (YkfDictDetailEntity item : list) {
                    map.put(item.getVal(), item.getName());
                }
                return map;
            }
        }
        return new HashMap<>();
    }

}
